var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var formidable  = require('formidable')
var path = require('path');
var fs = require('fs');

var ArticleSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  desc: {
    type: String,
    required: true,
    maxlength: 200,
  },
  content: {
    type: String,
    required: true,
    maxlength: 500,
  },
  stars: {
    type: Number,
    default: 0
  },
  praise: {
    type: Number,
    default: 0
  },
  articleImg: {
    type: Array,
    default: []
  },
  createTime: {
    type: Date,
    // 这里的Date.now是一个函数引用，会即时变化，而Date.now()是一个数字，传入一次不会改变，需要浏览器强制刷新才行
    default: Date.now
  }
})
var ArticleModel = mongoose.model('ArticleModel', ArticleSchema);

// GET lists
router.get('/get', (req, res, next) => {
  var currentPage = parseInt(req.query.currentPage) || 1;
  var pageSize = parseInt(req.query.pageSize) || 2;
  // 实现分页逻辑
  ArticleModel.count({}, (err, total) => {
    ArticleModel.find({}).skip((currentPage - 1) * pageSize).limit(pageSize).sort({createTime: -1}).exec((err, data) => {
      if (err) return next(err);
      return res.json({
        success: true,
        msg: '获取成功',
        total,
        pageSize,
        current: currentPage,
        pages: Math.ceil(total / pageSize),
        lists: data || [],
      })
    })
  })
})

// GET detail
router.get('/detail/:id', (req, res, next) => {
  var id = req.params.id;
  ArticleModel.findById({_id: id}, (err, data) => {
    if (err) return next(err);
    return res.json({
      detailItem: data,
      success: true,
      msg: '获取成功'
    })
  })
})

// POST add
router.post('/add', (req, res, next) => {
  var article = new ArticleModel(req.body);
  article.save((err) => {
    if (err) return next(err);
    return res.json({
      success: true,
      msg: '新增成功'
    });
  })
});

// PUT update
router.put('/add', (req, res, next) => {
  var id = req.body.id;
  ArticleModel.update({_id: id}, {$set: {...req.body}}).exec((err) => {
    if (err) return next(err);
    return res.json({
      success: true,
      msg: '编辑成功'
    })
  })
})

// DELETE delete
router.delete('/delete/:id', (req, res, next) => {
  var id = req.params.id;
  ArticleModel.remove({_id: id}, (err) => {
    if (err) return next(err);
    return res.json({
      success: true,
      msg: '删除成功'
    })
  })
})

// PUT star
router.put('/star/:id', (req, res, next) => {
  var id = req.params.id;
  ArticleModel.findById({_id: id}, (err, data) => {
    var starsCount = data.stars + 1;
    ArticleModel.update({_id: id}, {$set: {stars: starsCount}}, (err) => {
      if (err) return next(err);
      return res.json({
        success: true,
        msg: '加星成功'
      })
    })
  })
})

// PUT praise
router.put('/praise/:id', (req, res, next) => {
  var id = req.params.id;
  ArticleModel.findById({_id: id}, (err, data) => {
    var praiseCount = data.praise + 1;
    ArticleModel.update({_id: id}, {$set: {praise: praiseCount}}, (err) => {
      if (err) return next(err);
      return res.json({
        success: true,
        msg: '点赞成功'
      })
    })
  })
})

// POST upload file
router.post('/upload', async (req, res, next) => {
  // 使用formidable中间件进行图片上传
  var form = new formidable.IncomingForm();
  var uploadDir = path.join(__dirname, '../uploads');
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
  }
  form.uploadDir = uploadDir;
  form.encoding = 'utf-8';
  form.hash = 'md5';
  form.keepExtensions = true;
  await form.parse(req, (err, fields, files) => {
    if (err) return next(err);
    // 对文件进行重新命名
    var filePath = files.file.path;
    var extName = filePath.substring(filePath.indexOf('.'));
    var targetName = Date.now() + extName;
    var targetPath= path.join(uploadDir, targetName);
    fs.rename(filePath, targetPath, (err) => {
      if (err) return next(err);
      return res.send({success: true, msg: 'ok'});
    })
  });
  return; 
})

module.exports = router;
